import java.util.Arrays;

// key-value 模型
//实现一个哈希桶
public class HashBucket {
    private static class Node {
        private int key;
        private int value;
        public Node next;


        public Node(int key, int value) {
            this.key = key;
            this.value = value;
        }
    }


    //创建一个数组用来存放头节点
    private Node[]  array = new Node[DEFAULT_SIZE];
    private int size;   // 当前的数据个数
    private static final double LOAD_FACTOR = 0.75;
    private static final int DEFAULT_SIZE = 8;//默认桶的大小

    public void put(int key, int value) {
        //首先需要创建一个节点来接收我要插入的key和value
        Node newNode = new Node(key, value);
        int index = key % array.length;
        Node cur = array[index];
        Node prev = null;
        while(cur != null) {
            //遍历cur所在节点的链表，如果发现有相同key值则可以覆盖掉value
            if(cur.key == key) {
                cur.value = value;
                return;
            }
            prev = cur;
            cur = cur.next;
        }
        //到这里之后就到了尾部，可以进行插入了（头插和尾插都可以，这里写尾插）
        if(array[index] == null) {
            array[index] = newNode;
            size++;
            return;
        }
        prev.next = newNode;
        size++;
        //插完之后要检查是否需要扩容
        if(calcLoadFactor() >= LOAD_FACTOR){
            resize();
        }
    }

    //计算负载因子
    private double calcLoadFactor() {
        return (size * 1.0) / array.length;
    }

    /**
     * 为哈希桶的数组扩容
     */
    private void resize() {
        //创建一个新数组
        Node[] newArray = new Node[array.length * 2];
        //遍历原数组
        for(Node cur:array){
            Node newCur = null;
            while(cur != null) {
                //找到原数组中元素在新数组中的位置
                int newIndex = cur.key % newArray.length;
                newCur = newArray[newIndex];
                while(newCur != null) {
                    if(newCur.key == cur.key) {
                        newCur.value = cur.value;
                    }
                    newCur = newCur.next;
                }
                newCur = cur;
                if(newArray[newIndex] == null) {
                    newArray[newIndex] = newCur;
                }
                cur = cur.next;
            }
        }
        //再将新数组传给原数组
        array = newArray;
    }

    //获取key值对应的value值
    public int get(int key) {
        //先获取该key值对应的数组下标
        int index = key % array.length;
        Node cur = array[index];
        while(cur != null) {
            if(cur.key == key) {
                return cur.value;
            }
            cur = cur.next;
        }
        System.out.println("没有这个key值对应的value");
        return -1;
    }
}